package com.hys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.dao.DictMapper;
import com.hys.entity.Dict;
import com.hys.service.DictService;
import com.hys.util.BeanUtil;
import com.hys.vo.DictVO;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典类型表 服务实现类
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    public final static String enterType = "enterType";
    public final static String enterSize = "enterSize";
    public final static String major = "major";


    private Map<String, List<DictVO>> cacheMap = new HashMap<>();

    @Override
    public List<DictVO> getByDictType(String typeName) {
        // 检查缓存中是否存在对应的结果
        if (cacheMap.containsKey(typeName)) {
            return cacheMap.get(typeName);
        }

        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.lambda().eq(Dict::getType, typeName);
        List<Dict> list = list(qw);
        List<DictVO> dictVOS = BeanUtil.batchTransform(DictVO.class, list);
        // 将查询结果放入缓存
        cacheMap.put(typeName, dictVOS);
        return dictVOS;
    }

    @Override
    public Map<String, List<DictVO>> listByDictType(List<String> typeNames) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.lambda().in(Dict::getType, typeNames);
        List<Dict> list = list(qw);
        Map<String, List<Dict>> map = list.stream().collect(Collectors.groupingBy(Dict::getType));
        Map<String, List<DictVO>> resultMap = new HashMap<>();
        map.forEach((k, values)->{
            List<DictVO> dictVOS = BeanUtil.batchTransform(DictVO.class, values);
            resultMap.put(k, dictVOS);
        });
        return  resultMap;
    }

    @Override
    public Map<String, String> getByDictTypeRMap(String typeName) {
        List<DictVO> byDictType = getByDictType(typeName);
        Map<String, String> map = byDictType.stream().collect(Collectors.toMap(DictVO::getKey, DictVO::getValue));
        return map;
    }

    @Override
    public String getValueByKey(String typeName, String value) {

        List<DictVO> byDictType = getByDictType(typeName);
        Optional<DictVO> optional = byDictType.stream().filter(dict -> dict.getValue().equals(value)).findAny();
        if(optional.isPresent()){
            return optional.get().getKey();
        }
        return null;
    }


}
